package ar.uba.dc.cmovil.tripplanner.services;

import android.net.Uri;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by anton on 10/3/13.
 */
public class WikipediaService {
    private static WikipediaService instance;
    private Map<String, String> queryCache;

    private WikipediaService() {
        queryCache = new HashMap<String, String>();
    }

    public static WikipediaService instance() {
        if (instance == null) {
            instance = new WikipediaService();
        }
        return instance;
    }

    public String getWikiLink(String name) {
        return "http://es.wikipedia.org/wiki/" + Uri.encode(name).toString();
    }

    public void getDescriptionFor(final String query, final HttpTaskHandler<String> handler) {
        if (queryCache.containsKey(query)) {
            handler.onSuccess(queryCache.get(query));
        }

        WikipediaDescriptionTask task = new WikipediaDescriptionTask();
        task.setTaskHandler(new HttpTaskHandler<String>() {
            @Override
            public void onSuccess(String result) {
                queryCache.put(query, result);

                if (result == null || result.isEmpty()) {
                    handler.onFail();
                } else {
                    handler.onSuccess(result);
                }
            }

            @Override
            public void onFail() {
                handler.onFail();
            }
        });
        task.execute(query);
    }

}
